﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Coldairarrow.Business.Backstage.UserData;
using Coldairarrow.Business.BTB_StaffUsers;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Util;
using Coldairarrow.Util.lib;
using Coldairarrow.Util.Other;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using ThoughtWorks.QRCode.Codec;
using WxPayAPI;
using WxPayAPI.lib;

namespace Coldairarrow.Api.Controllers.PersonalCenter
{
    [Route("/PersonalCenter/[controller]/[action]")]
    public class BTB_UserController : BaseApiController
    {
        #region DI
        public readonly IWebHostEnvironment _webHostEnvironment;
        public readonly IBS_UserRebateBusiness _UserRebateBusiness;
        public BTB_UserController(IBTB_StaffUserBusiness bTB_StaffUserBus, IBS_UserRebateBusiness userRebateBusiness, IWebHostEnvironment webHostEnvironment)
        {
            _bTB_StaffUserBus = bTB_StaffUserBus;
            _webHostEnvironment = webHostEnvironment;
            _UserRebateBusiness = userRebateBusiness;
        }

        IBTB_StaffUserBusiness _bTB_StaffUserBus { get; }
        /// <summary>
        ///  用户信息查看
        /// </summary>
        /// <returns></returns>
        #endregion
        [HttpPost]
        public BTB_StaffUser GetTheData()
        {
            return _bTB_StaffUserBus.GetTheDataAsync();
        }
        /// <summary>
        /// 用户信息修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task SaveData(BTB_StaffUser data)
        {
            await _bTB_StaffUserBus.UpdateUserAsync(data);
        }

        /// <summary>
        /// 个人中心——获取本人默认地址（无默认，取第一个）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetUserDFAddress()
        {
            return _bTB_StaffUserBus.GetDFAddressAsnyc();
        }


        /// <summary>
        /// 个人中心——获取本人积分和收益
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetUserCPoint()
        {
            return _bTB_StaffUserBus.GetUserCPointAsync();
        }


        /// <summary>
        /// 个人中心——获取浏览、收藏和评价数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetUserSCAData()
        {
            return _bTB_StaffUserBus.GetVCRDataAsync();
        }


        /// <summary>
        /// 个人中心——获取订单统计数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetOrderSumAData()
        {
            return _bTB_StaffUserBus.GetOrderSumDataAsync();
        }

        /// <summary>
        ///  个人中心——获取用户收益明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetsReabteList(PageInput<ConditionDTO> input)
        {
            var sumData = _UserRebateBusiness.GetSumData();
            var list = await _UserRebateBusiness.GetDataListAsync(input);

            var data = new {
                SumData = sumData,
                ListData = list
            };

            return data;
        }

        /// <summary>
        ///  个人中心——获取用户收益合计明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public object GetsSumReabteList(PageInput<ConditionDTO> input)
        {
            var sumData = _UserRebateBusiness.GetSumData();
            return sumData;
        }

        /// <summary>
        /// 个人中心获取个人关系图
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public PDiagramDTO GetMyDiagrams(GetDiagramInput input)
        {
            return _bTB_StaffUserBus.GetMyDiagram(input);
        }

        /// <summary>
        /// 前台——H5获取微信分享信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetShareInfo(UrlDTO input)
        {

            string code = _bTB_StaffUserBus.GetMyYQCode();

            var url = HttpUtility.UrlDecode(input.url);

            string appId = WxPayGZHConfig.GetConfig().GetAppID();
            string timestamp = GetTimeStamp();
            string nonceStr = GenerateNonceStr();
            MiniPackage.AccessTokenManage.RequestAccessToken();

            string ticket = MiniPackage.AccessTokenManage.JsapiTicket;
            string signature = MakeGzhShareSign(url, nonceStr, timestamp, ticket);

            var obj = new {
                code,
                appId,
                timestamp,
                nonceStr,
                signature
            };

            return obj;
        }


        private string MakeGzhShareSign(string url, string noncestr, string timestamp, string ticket)
        {
            //转url格式
            string string1 = "jsapi_ticket=" + ticket;
            string1 += "&noncestr=" + noncestr;
            string1 += "&timestamp=" + timestamp;
            string1 += "&url=" + url;

            Serilog.Log.Information("获取签名字符串:"+string1);

            SHA1 sha = SHA1.Create();
            byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(string1));
            //Console.WriteLine("正确生成:" + BitConverter.ToString(bytResult).Replace("-", ""));
            //Console.ReadKey();

            return BitConverter.ToString(bytResult).Replace("-", "").ToLower();
        }

        //[HttpGet]
        //[NoCheckJWT]
        //public string MakeShareSign(string str1)
        //{

        //    SHA1 sha = SHA1.Create();
        //    byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str1));
        //    //Console.WriteLine("正确生成:" + BitConverter.ToString(bytResult).Replace("-", ""));
        //    //Console.ReadKey();

        //    return BitConverter.ToString(bytResult).Replace("-", "");
        //}

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// 生成随机串，随机串包含字母或数字
        /// </summary>
        /// <returns></returns>
        private static string GenerateNonceStr()
        {
            RandomGenerator randomGenerator = new RandomGenerator();
            return randomGenerator.GetRandomUInt().ToString();
        }

        /// <summary>
        /// 前台——获取搜索提示列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<GetSearchDTO>> GetSearcGoods([FromBody]GetSearchDTO input)
        {
            var list = await _bTB_StaffUserBus.GetSearchGoodList(input);

            return list;
        }

        /// <summary>
        /// 获取邀请二维码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetERCode()
        {
            try
            {
                //初始化二维码生成工具
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                qrCodeEncoder.QRCodeVersion = 0;
                qrCodeEncoder.QRCodeScale = 10;

                //获取个人信息
                string url = _bTB_StaffUserBus.GetEQImgData();

                var udata = _bTB_StaffUserBus.GetUserData();

                //将字符串生成二维码图片
                Bitmap image = qrCodeEncoder.Encode(url, Encoding.Default);

                //保存为PNG到内存流  
                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);


                //var QCodeData = ms.GetBuffer();

                string imgStr = ToBase64(image);

                string html = "<html><style>"
                + "*{margin:0;padding:0;}.contaniner{width:1024px;min-height:1334px;margin:0 auto;position:relative;overflow:hidden;}.bgimg{width:100%;}.invbox{width:700px;height:570px;left:50%;margin-left:-350px;position:absolute;top:830px}.invnum{width:450px;height:130px;line-height:120px;text-align:center;font-size:53px;font-weight:800;color:#bd7c43;letter-spacing:14px;font-family:PingFang SC}.qrbg{position: relative;width:320px;height:320px;margin:0 auto;margin-top:135px;}.qrimg{position: absolute;top:50%;left:50%;margin-left:-130px;margin-top:-140px;width:260px;height:260px;}</style><body><div class=contaniner><img class=bgimg src="
                + ""
                + ">" 
                + "<div class=invbox><div class=invnum>"+ udata.User_YQCode + "</div><div class=qrbg>"
                + "<img class=qrimg src='data:image/png;base64," + imgStr + "'></div></div></div></body></html>";

                //string html = "<!doctypehtml><html lang='en'><meta charset='UTF-8'>"
                // + "<meta content = \"width=device-width,initial-scale=1\"name = viewport><title></title>"
                // + "<style>.contaniner{ width: 1024px; min-height:1334px; margin: 0 auto; position: relative} .sImg{ width:1024px;} .i_dback{"
                // + "position: fixed; top: 30px; left: 25px; z-index:999; font-size:50px; color:#fff}.content{overflow:hidden;position:relative}.invbox{width:640px;height:661px;left:50%;margin-left:-320px;position:absolute;bottom:60px}.content .copyinv{width:528px;height:80px;margin:0 auto;display:flex;align-items:center;justify-content:space-between}.content .copyinv .invnum{display:block;line-height:76px;width:330px;text-align:center;text-indent:30px;font-size:36px;font-weight:800;color:#bd7c43;letter-spacing:14px;font-family:PingFang SC}.qrimg{display:flex;justify-content:center;align-items:center;width:210px;height:210px;margin:0 auto;margin-top:114px}  .imgs{width:210px;height:210px;}</style>"
                // + "<body><div class='contaniner'><i class=\"i_dback icon\"></i><div class='content' ><img class='sImg' src = ''>"
                // + "<div class='invbox'><div class='copyinv'><span class='invnum' id = 'yqtxt'>" + udata.User_YQCode
                // + "</span>"
                // + "</div><div class= 'qrimg'><img class='imgs' src =\"data:image/png;base64," + imgStr + "\"></div></div></div></div></body></html>";

                string imgName = "QRCode-" + udata.User_YQCode + ".jpg";
                string sPath = _webHostEnvironment.WebRootPath + "/imgeOutput/" + imgName;
                string mPath = "/imgeOutput/" + imgName;
                HtmlToImg.HtmlTextConvertToImg(html, sPath, _webHostEnvironment.WebRootPath);

                var data = new
                {
                    ImgPath= mPath,
                    Code = udata.User_YQCode,
                    Name = udata.NickName,
                    HeadImg = udata.HeadPortrait,
                    HType = udata.HeadType
                };

                return data;
            }
            catch (Exception ex)
            {
                throw new BusException("生成二维码失败！",-3);
            }

            return "";
        }


        //图片转为base64编码的文本   
        private string ToBase64(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                return strbaser64;
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        /// <summary>
        /// 生成小程序二维码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object GetXcxERCode()
        {
            var codePath = _bTB_StaffUserBus.GetXcxEQImgData(_webHostEnvironment.WebRootPath);

            var imgStr = FileToBate64(_webHostEnvironment.WebRootPath + codePath);

            var udata = _bTB_StaffUserBus.GetUserData();

            string html = "<html><style>"
               + "*{margin:0;padding:0;}.contaniner{width:1024px;min-height:1334px;margin:0 auto;position:relative;overflow:hidden;}.bgimg{width:100%;}.invbox{width:700px;height:570px;left:50%;margin-left:-350px;position:absolute;top:830px}.invnum{width:450px;height:130px;line-height:120px;text-align:center;font-size:53px;font-weight:800;color:#bd7c43;letter-spacing:14px;font-family:PingFang SC}.qrbg{position: relative;width:320px;height:320px;margin:0 auto;margin-top:135px;}.qrimg{position: absolute;top:50%;left:50%;margin-left:-130px;margin-top:-140px;width:260px;height:260px;}</style><body><div class=contaniner><img class=bgimg src="
               + ""
               + ">"
               + "<div class=invbox><div class=invnum>" + udata.User_YQCode + "</div><div class=qrbg>"
               + "<img class=qrimg src='data:image/png;base64," + imgStr + "'></div></div></div></body></html>";

            string imgName = "XQRCode-" + udata.User_YQCode + ".jpg";
            string sPath = _webHostEnvironment.WebRootPath + "/imgeOutput/" + imgName;
            string mPath = "/imgeOutput/" + imgName;
            HtmlToImg.HtmlTextConvertToImg(html, sPath, _webHostEnvironment.WebRootPath);

            var data = new
            {
                ImgPath = mPath,
                Code = udata.User_YQCode,
                Name = udata.NickName,
                HeadImg = udata.HeadPortrait,
                HType = udata.HeadType
            };

            return data;

        }

        private static string FileToBate64(string fileName)
        {
            string strRet = "";
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                strRet = Convert.ToBase64String(bytes);
                fs.Close();
            }
            catch (Exception ex)
            {
                strRet = null;
            }

            return strRet;
        }
    }
}
